﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace PID调试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            cbCom.Items.Clear();
            cbCom.Items.AddRange(ports);
            cbCom.SelectedIndex = 0;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Text == "开始")
            {
                toolStripButton1.Text = "停止";
                Com.PortName = cbCom.Text;
                Com.Open();
                strRx = "";
            }
            else
            {
                toolStripButton1.Text = "开始";
                Com.Close();
            }
        }
        string strRx;
        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string rx=Com.ReadExisting();
            strRx += rx;
            while(true)
            {
                int h1, h2;
                h1 = strRx.IndexOf('#');
                if (h1 == -1)
                {
                    strRx = "";
                    break;
                }
                strRx = strRx.Substring(h1);
                h2 = strRx.IndexOf('@');
                if (h2 == -1)
                    break;
                string pid = strRx.Substring(1, h2-1);                
                if (textBox1.Text.Length > 30000)
                    textBox1.Clear();
                this.Invoke((EventHandler)(delegate
                    {
                        textBox1.AppendText(pid + "\r\n");
                        string[] _pid = pid.Split(',');
                        for (int i = 0; i < listView1.Items.Count; i++)
                        {
                            ListViewItem li = listView1.Items[i];
                            li.SubItems[1].Text = _pid[i];
                        }
                        chart1.Series[0].Points.AddY(double.Parse(_pid[1]));
                        chart1.Series[1].Points.AddY(double.Parse(_pid[0]));
                    }));                
                strRx = strRx.Substring(h2+1);
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                ListViewItem li = listView1.Items[i];
                li.SubItems[1].Text = "";
            }
            chart1.Series[0].Points.Clear();
            chart1.Series[1].Points.Clear();
        }
    }
}
